<template>
  <div class="page-view">
    <div class="map-view">
      <MyMap ref="myMap">
        <MapGeo v-if="layers" :json="layers" :stroke="{ color: '#f0f', width: 2 }"></MapGeo>
        <MapMarker
          v-if="dataMarker"
          :data="dataMarker"
          :cluster="false"
          :scale="0.7"
          :distance="10"
          @show="clickPoint"
          :popup="{ width: '500px', title: '评价结果' }"
        >
          <div >
            <a-descriptions title="肥力评估" :column="1" bordered size="small">
              <a-descriptions-item label="样本编号" span="1">
                {{ markerInfo['YDBH'] || 0 }}
              </a-descriptions-item>
              <a-descriptions-item label="OM得分" span="1">
                {{ markerInfo['OM得分'] || 0 }}
              </a-descriptions-item>
              <a-descriptions-item label="TN得分" span="1">
                {{ markerInfo['TN得分'] || 0 }}
              </a-descriptions-item>
              <a-descriptions-item label="AP得分" span="1">
                {{ markerInfo['AP得分'] || 0 }}
              </a-descriptions-item>
              <a-descriptions-item label="AK得分" span="1">
                {{ markerInfo['AK得分'] || 0 }}
              </a-descriptions-item>
              <a-descriptions-item label="肥力得分" span="1">
                {{ markerInfo['肥力得'] || 0 }}
              </a-descriptions-item>
              <a-descriptions-item label="肥力等级" span="1">
                {{ markerInfo['肥力等'] || '' }}
              </a-descriptions-item>
            </a-descriptions>
            <br />
            <a-descriptions title="清洁度评价" :column="1" bordered size="small">
              <a-descriptions-item label="NI清洁度" span="1">
                {{ markerInfo['NI_level'] }}
              </a-descriptions-item>
              <a-descriptions-item label="HG清洁度" span="1">
                {{ markerInfo['HG_level'] }}
              </a-descriptions-item>
              <a-descriptions-item label="AS清洁度" span="1">
                {{ markerInfo['AS_level'] }}
              </a-descriptions-item>
              <a-descriptions-item label="PB清洁度" span="1">
                {{ markerInfo['PB_level'] }}
              </a-descriptions-item>
              <a-descriptions-item label="CD清洁度" span="1">
                {{ markerInfo['Cd_level'] }}
              </a-descriptions-item>
              <a-descriptions-item label="CR清洁度" span="1">
                {{ markerInfo['CR_level'] }}
              </a-descriptions-item>
              <a-descriptions-item label="综合清洁度" span="1">
                {{ markerInfo['POLLUTION'] }}
              </a-descriptions-item>
            </a-descriptions>
          </div>
        </MapMarker>
        <!-- <MapHeat v-if="dataHeat" :data="dataHeat"></MapHeat> -->
        <!-- <div class="left-tree">
          <div class="warp">
            <div class="tree-content" v-if="isShowTree">
              <div class="header">资源目录</div>
              <div>
                <MapTree></MapTree>
              </div>
            </div>
            <div class="close" @click="isShowTree = !isShowTree">
              <a-icon type="caret-left" v-if="isShowTree" />
              <a-icon type="caret-right" v-if="!isShowTree" />
            </div>
          </div>
        </div> -->
      </MyMap>
    </div>
    <div class="select-filds">
      <a-form :labelCol="{ span: 5 }" :wrapperCol="{ span: 19 }">
        <a-form-item label="区域">
          <a-tree-select
            v-model="searchForm.xzqdm"
            :treeData="city"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :replaceFields="{
              value: 'dicCode',
              label: 'dicValue'
            }"
            placeholder="请选择区域"
            style="width: 100%"
          >
          </a-tree-select>
        </a-form-item>
        <a-form-item label="类型">
          <a-select v-model="searchForm.type" style="width: 100%">
            <a-select-option value="fl">肥力评估</a-select-option>
            <a-select-option value="fx">清洁度评价</a-select-option>
          </a-select>
        </a-form-item>
        <div style="text-align: center">
          <a-button type="primary" @click="handleClick"> 评价 </a-button>
        </div>
      </a-form>
    </div>
    <div class="result-icon">
      <div class="icon-item"><a-icon type="table" :class="{ 'active': showTable}" @click="showTable = !showTable" /></div>
    </div>
    <div class="reslut-filds">
      <EchartsBox :data="cahrtData" :type="searchType"></EchartsBox>
    </div>
    <div class="loading-warp" v-if="showLoading">
      <div class="loading-out">
        <Loading></Loading>
        <div class="text">分析中</div>
      </div>
    </div>

    <a-drawer
      placement="bottom"
      :visible="showTable"
      :mask="false"
      @close="showTable = !showTable"
      :height="360"
      :bodyStyle="{ padding: '10px 10px 0px 10px' }"
    >
      <div slot="title" style="display: flex; justify-content: space-between">
        <div>评估结果</div>
        <div style="margin-right: 40px">
          <a-button type="link" size="small" icon="download" @click="exportExcel">导出</a-button>
        </div>
      </div>
      <div>
        <a-table
          rowKey="id"
          :dataSource="valueData"
          size="small"
          :bordered="false"
          :columns="columns"
          :pagination="pagination"
          :customRow="customRow"
        >
        </a-table>
      </div>
    </a-drawer>
  </div>
</template>

<script>
import { MyMap, MapGeo, MapMarker, MapHeat } from '@/map'
import { queryAllcity, queryCityGeo } from '@/api/common'
import MapTree from '@/views/home/components/tree'
import EchartsBox from './components/chart.vue'
import Loading from '@/components/loading'
import { QueryBySQLParameters, QueryService } from '@supermap/iclient-ol'
import red from '@/assets/icon/red.png'
// import lightGreen from '@/assets/icon/c-lightGreen.png'
// import orange from '@/assets/icon/orange.png'
// import icon1 from '@/assets/icon/icon1.png'
// import icon2 from '@/assets/icon/icon2.png'
// import icon3 from '@/assets/icon/icon3.png'
// import icon4 from '@/assets/icon/icon4.png'
// import icon5 from '@/assets/icon/icon5.png'
import { export_array_to_excel as exportArrayToExcel } from '@/utils/excel'

const Icon = {
  重度污染: '#FFff00',
  中度污染: '#ffb900',
  轻度污染: '#ff5500', // red,
  尚清洁: '#ffff00', // orange,
  清洁: '#55ff00' // lightGreen
}

const colors = {
  极高: '#38a800', // icon5,
  高: '#98e600', // icon4,
  中: '#e6e600', // icon3,
  低: '#ee9900', // icon2,
  极低: '#8f1a00' // icon1
}

export default {
  name: 'Inference',
  components: {
    MyMap,
    MapMarker,
    MapGeo,
    MapHeat,
    Loading,
    MapTree,
    EchartsBox
  },
  data () {
    return {
      isShowTree: true,
      showLoading: false,
      city: [],
      layers: undefined,
      markerInfo: {},
      searchForm: {
        xzqdm: '110117',
        type: 'fl'
      },
      searchType: 'fl',
      showTable: false,
      dataMarker: undefined,
      // dataHeat: undefined,
      valueData: [],
      columns: [],
      pagination: {
        pageSize: 5
      },
      cahrtData: []
    }
  },
  created () {
    this.fetchCity()
    this.handleClick()
  },
  methods: {
    clickPoint (marker) {
      this.markerInfo = {
        ...marker.items[0].properties
      }
      this.pointHightlight(marker.items[0])
    },
    // 行点击
    customRow (record) {
      return {
        on: {
          click: () => {
           this.pointHightlight(record)
          }
        }
      }
    },
    // 高亮选中
    pointHightlight (marker) {
      this.dataMarker = this.dataMarker.map(item => {
        if (item.properties.YDBH === marker.properties.YDBH) {
          this.$refs.myMap.moveTo([ item.coordinate[0], item.coordinate[1] ])
        }
        return {
          ...item,
          style: item.properties.YDBH === marker.properties.YDBH ? undefined : this.setMarkerStyle(item).style,
          src: item.properties.YDBH === marker.properties.YDBH ? red : undefined
        }
      })
    },
    setMarkerStyle (marker) {
      if (this.searchType === 'fl') {
        return {
          style: {
            fill: colors[marker.properties['肥力等']] || '#fff',
            radius: 5
          }
        }
      } else {
        return {
          style: {
            fill: Icon[marker.properties['POLLUTION']] || '#fff',
            radius: 5
          }
        }
      }
    },
    async fetchCity () {
      try {
        const { data } = await queryAllcity()
        this.city = data[0].children
      } catch (err) {
        throw err
      }
    },
    handleChange () {
      this.layers = undefined
      if (this.searchForm.xzqdm) {
        queryCityGeo({
          xzqdm: this.searchForm.xzqdm
        }).then((res) => {
          this.layers = JSON.parse(res.data)
        })
      }
    },
    handleClick () {
      this.dataMarker = undefined
      this.dataHeat = undefined
      this.searchType = this.searchForm.type
      this.handleChange()
      this.evaluateResult()
    },
    /**
     * 分析
     */
    async evaluateResult () {
      const url = window.service.mapService + '/iserver/services/map-LYSP/rest/maps/平谷园林草地样点评价@业务数据'
      this.showLoading = true
      try {
        const sqlParam = new QueryBySQLParameters({
          queryParams: {
            name: '平谷园林草地样点评价@业务数据3',
            attributeFilter: `ZLDWDM like '${this.searchForm.xzqdm}%'`
          },
          startRecord: 0
        })
        const res = await new QueryService(url).queryBySQL(sqlParam)

        if (res.result.totalCount) {
          this.valueData = res.result.recordsets[0].features.features
          this.showTable = true
          if (this.searchForm.type === 'fl') {
            this.fertilitykData(this.valueData)
            this.columns = [
              {
                title: '序号',
                key: 'index',
                fixed: true,
                customRender: (text, record, index) => index + 1
              },
              {
                title: '样点编号',
                key: 'YDBH',
                dataIndex: 'properties.YDBH'
              },
              {
                title: '行政区',
                key: 'ZLDWMC',
                dataIndex: 'properties.ZLDWMC'
              },
              {
                title: 'OM得分',
                key: 'OM得分',
                dataIndex: 'properties.OM得分',
                customRender: (text) => text || 0
              },
              {
                title: 'TN得分',
                key: 'TN得分',
                dataIndex: 'properties.TN得分',
                customRender: (text) => text || 0
              },
              {
                title: 'AP得分',
                key: 'AP得分',
                dataIndex: 'properties.AP得分',
                customRender: (text) => text || 0
              },
              {
                title: 'AK得分',
                key: 'AK得分',
                dataIndex: 'properties.AK得分',
                customRender: (text) => text || 0
              },
              {
                title: '肥力得分',
                key: '肥力得',
                dataIndex: 'properties.肥力得',
                customRender: (text) => text || 0
              },
              {
                title: '肥力等级',
                key: '肥力等',
                dataIndex: 'properties.肥力等',
                customRender: (text) => text || 0
              }
            ]
          } else {
            this.riskData(this.valueData)
            this.columns = [
              {
                title: '序号',
                key: 'index',
                fixed: true,
                customRender: (text, record, index) => index + 1
              },
              {
                title: '样点编号',
                key: 'YDBH',
                dataIndex: 'properties.YDBH'
              },
              {
                title: '坐落单位',
                key: 'ZLDWMC',
                dataIndex: 'properties.ZLDWMC'
              },
              {
                title: 'NI清洁度',
                key: 'NI_level',
                dataIndex: 'properties.NI_level'
              },
              {
                title: 'HG清洁度',
                key: 'HG_level',
                dataIndex: 'properties.HG_level'
              },
              {
                title: 'AS清洁度',
                key: 'AS_level',
                dataIndex: 'properties.AS_level'
              },
              {
                title: 'PB清洁度',
                key: 'PB_level',
                dataIndex: 'properties.PB_level'
              },
              {
                title: 'CD清洁度',
                key: 'Cd_level',
                dataIndex: 'properties.Cd_level'
              },
              {
                title: 'CR清洁度',
                key: 'CR_level',
                dataIndex: 'properties.CR_level'
              },
              {
                title: '综合清洁度',
                key: 'POLLUTION',
                dataIndex: 'properties.POLLUTION'
              }
            ]
          }
        }
        this.showLoading = false
      } catch (err) {
        this.showLoading = false
        this.$message.error(err.data || '分析失败')
      }
    },
    // 清洁度
    riskData (data) {
      const chatType = {
        重度污染: 0,
        中度污染: 0,
        轻度污染: 0,
        尚清洁: 0,
        清洁: 0
      }
      this.dataMarker = data.map((marker) => {
        const risk = marker.properties['POLLUTION']
        chatType[risk] = chatType[risk] ? chatType[risk] + 1 : 1
        return {
          ...marker,
          coordinate: [Number(marker.properties['布设经']), Number(marker.properties['布设纬'])],
          ...this.setMarkerStyle(marker)
        }
      })
      this.cahrtData = Object.keys(chatType).map((key) => {
        return { name: key, value: chatType[key] }
      }).filter(item => item.name !== '0')
      // this.dataHeat = data.map(marker => {
      //   return {
      //     coordinate: [marker.properties['布设经'], marker.properties['布设纬']]
      //   }
      // })
    },
    /**
     * 肥力
     * @param data
     */
    fertilitykData (data) {
      const chatType = {
        极高: 0,
        高: 0,
        中: 0,
        低: 0,
        极低: 0
      }
      this.dataMarker = data.map((marker) => {
        const fertility = marker.properties['肥力等']
        chatType[fertility] = chatType[fertility] ? chatType[fertility] + 1 : 1
        return {
          ...marker,
          coordinate: [Number(marker.properties['布设经']), Number(marker.properties['布设纬'])],
          ...this.setMarkerStyle(marker)
        }
      })
      this.cahrtData = Object.keys(chatType).map((key) => {
        return { name: key || '无等级', value: chatType[key] }
      })
    },
    // 导出excel
    exportExcel () {
      if (!this.valueData.length) {
        this.$message.error('无导出数据')
        return false
      }
      exportArrayToExcel({
        sheet: [
          {
            columns: this.columns,
            data: this.valueData,
            sheetName: this.searchForm.xzqdm
          }
        ],
        filename: '分析结果'
      })
    }
  }
}
</script>

<style lang="less" scoped>
.page-view {
  position: relative;
  height: 100%;
  .map-view {
    position: absolute;
    top: -24px;
    right: -24px;
    bottom: -24px;
    left: -24px;
  }
}
.select-filds {
  position: absolute;
  top: 0;
  right: 0;
  padding: 24px;
  width: 360px;
  border-radius: 4px;
  background: #ffffff;
  box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.03);
}
.group {
  font-size: 16px;
}
.left-tree {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 9;
  height: 100%;
  background: #ffffff;
  .tree-content {
    width: 300px;
    .header {
      position: relative;
      padding: 0 14px;
      height: 40px;
      font-size: 16px;
      color: #222222;
      background: #ebeef5;
      line-height: 40px;
    }
  }
  .close {
    position: absolute;
    top: 50%;
    right: -20px;
    width: 20px;
    height: 100px;
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-left: none;
    border-radius: 0 2px 2px 0;
    line-height: 100px;
    transform: translateY(-50%);
    cursor: pointer;
    background: #ebeef5;
  }
}
.loading-warp {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.03);
  .loading-out {
    display: inline-block;
    padding: 16px 24px;
    border-radius: 4px;
    background: rgba(0, 0, 0, 0.5);
  }
  .text {
    text-align: center;
    color: #ffffff;
  }
}
.reslut-filds {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  width: 360px;
  height: 300px;
  background: #ffffff;
}
.result-icon {
  position: absolute;
  top: 40%;
  right: 0;
  .icon-item {
    margin: 8px 0;
    padding: 4px 8px;
    font-size: 20px;
    font-weight: bold;
    border-radius: 4px;
    background: #ffffff;
  }
  .active {
    color: @primary-color;
  }
}
</style>
